package cn.com.surker.task;

import cn.com.surker.enums.material.MaterialContractTypeEnum;
import cn.com.surker.material.service.impl.MaterialBillServiceImpl;
import cn.com.surker.redis.RedisUtils;
import cn.com.surker.system.dao.DataSourceInfoDao;
import cn.com.surker.system.dao.SysOriginDao;
import cn.com.surker.system.entity.DataSourceInfo;
import cn.com.surker.system.entity.SysOrigin;
import cn.com.surker.util.DateUtil;
import cn.com.surker.util.ReportDateUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.transaction.RollbackException;
import java.util.Date;
import java.util.List;

/**
 * @Author lucky
 * @create 2024年12月13 23:29
 * @desc
 */
@Slf4j
@Configuration
@EnableScheduling
public class MaterialTask {

    /**计算购进报表redis锁**/
    private final static String MATERIAL_WEIGHT_REDIS_LOOK_KEY = "MATERIAL_WEIGHT_REDIS_LOOK_KEY";

    @Resource
    private RedisUtils redisUtils;
    @Resource
    private MaterialBillServiceImpl materialBillService;
    @Resource
    private DataSourceInfoDao dsDao;
    @Resource
    private SysOriginDao originDao;

    public static void main(String[] args){
        Date nowDate = new Date();

        Date beforeDate = DateUtil.convertBeforeMonthDate(nowDate, 1);
        String startTime = ReportDateUtils.getMaterialMonthStartTime(nowDate, true);
        String endTime = ReportDateUtils.getMaterialMonthEndTime(nowDate, true);
        String beforeStartTime = ReportDateUtils.getMaterialMonthStartTime(beforeDate, true);
        String beforeEndTime = ReportDateUtils.getMaterialMonthEndTime(beforeDate, true);
        String today = endTime.substring(0,7);
        String beforeToday = beforeEndTime.substring(0,7);
        Date flagDate = DateUtil.convertDate(startTime.substring(0,7) + "-25 08:30:00");
        Date maxFlagDate = DateUtil.convertBeforeMonthDate(DateUtil.convertDate(endTime.substring(0,7) + "-27 08:30:00"), -1);

        System.out.println(startTime + "\t" + endTime + "\t" + beforeEndTime + "\t" + beforeStartTime);
        System.out.println(today + "\t" + beforeToday + "\t" + DateUtil.convertString(flagDate) + "\t" + DateUtil.convertString(maxFlagDate));
    }

    /**
     * 计算结算明细
     */
    @Scheduled(cron = "43 11 * * * ?")
    @Transactional(rollbackFor = RollbackException.class,propagation = Propagation.REQUIRED)
    public void billReportTime() {
        Date nowDate = new Date();

        Date beforeDate = DateUtil.convertBeforeMonthDate(nowDate, 1);
        String startTime = ReportDateUtils.getMaterialMonthStartTime(nowDate, true);
        String endTime = ReportDateUtils.getMaterialMonthEndTime(nowDate, true);
        String beforeStartTime = ReportDateUtils.getMaterialMonthStartTime(beforeDate, true);
        String beforeEndTime = ReportDateUtils.getMaterialMonthEndTime(beforeDate, true);
        String today = endTime.substring(0,7);
        String beforeToday = beforeEndTime.substring(0,7);
        Date flagDate = DateUtil.convertDate(startTime.substring(0,7) + "-25 08:30:00");
        Date maxFlagDate = DateUtil.convertBeforeMonthDate(DateUtil.convertDate(endTime.substring(0,7) + "-27 08:30:00"), -1);
        Integer flag = 0;
        if (nowDate.getTime() > flagDate.getTime() && nowDate.getTime() < maxFlagDate.getTime()) {
            flag = 1;
        }
//        startTime = "2025-01-25 08:30:00";
//        endTime = "2025-02-25 08:30:00";
//        today = "2025-02";
        try {
            QueryWrapper<DataSourceInfo> dsQuery = new QueryWrapper<>();
            dsQuery.eq("status", 0);
            dsQuery.eq("type", 0);
            dsQuery.inSql("id", "select ds_id from data_relation where origin_id in " +
                    " (select id from sys_origin where status = 0 and type = 2)");
            List<DataSourceInfo> dsList = dsDao.selectList(dsQuery);
            if (dsList == null || dsList.size() == 0)
                return;
            Boolean looked = redisUtils.hasLock(MATERIAL_WEIGHT_REDIS_LOOK_KEY);//获取锁是否存在
            if (!looked) {
                redisUtils.acquireLock(MATERIAL_WEIGHT_REDIS_LOOK_KEY);//不存在枷锁
                for (int i = 0; i < dsList.size(); i++) {
                    SysOrigin origin = originDao.queryByDsId(dsList.get(i).getId());
                    if (origin == null)
                        continue;
                    try {
                        materialBillService.calcMaterialDetail(today,origin.getId(), MaterialContractTypeEnum.ZC.getCode(), null, null, "系统管理员", 1);
                    } catch (Exception e) {
                        log.error("计算主材结算数据错误" + e.getMessage());
                        continue;
                    }
                    try {
                        materialBillService.calcMaterialDetail(today,origin.getId(), MaterialContractTypeEnum.YSC.getCode(), null, null, "系统管理员", 1);
                    } catch (Exception e) {
                        log.error("计算运输结算数据错误" + e.getMessage());
                        continue;
                    }
                    if (today.indexOf("-12") != -1) {
                        try {
                            materialBillService.calcMaterialDetail(today + "附", origin.getId(), MaterialContractTypeEnum.ZC.getCode(), null, null, "系统管理员", 1);
                        } catch (Exception e) {
                            log.error("计算主材结算数据错误" + e.getMessage());
                            continue;
                        }
                        try {
                            materialBillService.calcMaterialDetail(today + "附", origin.getId(), MaterialContractTypeEnum.YSC.getCode(), null, null, "系统管理员", 1);
                        } catch (Exception e) {
                            log.error("计算运输结算数据错误" + e.getMessage());
                            continue;
                        }
                    }
                    if (flag == 1) {
                        try {
                            materialBillService.calcMaterialDetail(beforeToday,origin.getId(), MaterialContractTypeEnum.ZC.getCode(), null, null, "系统管理员", 1);
                        } catch (Exception e) {
                            log.error("计算运输结算数据错误" + e.getMessage());
                            continue;
                        }
                        try {
                            materialBillService.calcMaterialDetail(beforeToday,origin.getId(), MaterialContractTypeEnum.YSC.getCode(), null, null, "系统管理员", 1);
                        } catch (Exception e) {
                            log.error("计算运输结算数据错误" + e.getMessage());
                            continue;
                        }

                        if (beforeToday.indexOf("-12") != -1) {
                            try {
                                materialBillService.calcMaterialDetail(beforeToday + "附",origin.getId(), MaterialContractTypeEnum.ZC.getCode(), null, null, "系统管理员", 1);
                            } catch (Exception e) {
                                log.error("计算运输结算数据错误" + e.getMessage());
                                continue;
                            }
                            try {
                                materialBillService.calcMaterialDetail(beforeToday + "附",origin.getId(), MaterialContractTypeEnum.YSC.getCode(), null, null, "系统管理员", 1);
                            } catch (Exception e) {
                                log.error("计算运输结算数据错误" + e.getMessage());
                                continue;
                            }
                        }
                    }
                }
            } else {
                Thread.sleep(300L);
                looked = redisUtils.hasLock(MATERIAL_WEIGHT_REDIS_LOOK_KEY);//获取锁是否存在
                if (!looked) {
                    for (int i = 0; i < dsList.size(); i++) {
                        SysOrigin origin = originDao.queryByDsId(dsList.get(i).getId());
                        if (origin == null)
                            continue;
                        try {
                            materialBillService.calcMaterialDetail(today,origin.getId(), MaterialContractTypeEnum.ZC.getCode(), null, null, "系统管理员", 1);
                        } catch (Exception e) {
                            log.error("计算运输结算数据错误" + e.getMessage());
                            continue;
                        }
                        try {
                            materialBillService.calcMaterialDetail(today,origin.getId(), MaterialContractTypeEnum.YSC.getCode(), null, null, "系统管理员", 1);
                        } catch (Exception e) {
                            log.error("计算运输结算数据错误" + e.getMessage());
                            continue;
                        }
                        if (today.indexOf("-12") != -1) {
                            try {
                                materialBillService.calcMaterialDetail(today + "附",origin.getId(), MaterialContractTypeEnum.ZC.getCode(), null, null, "系统管理员", 1);
                            } catch (Exception e) {
                                log.error("计算运输结算数据错误" + e.getMessage());
                                continue;
                            }
                            try {
                                materialBillService.calcMaterialDetail(today + "附",origin.getId(), MaterialContractTypeEnum.YSC.getCode(), null, null, "系统管理员", 1);
                            } catch (Exception e) {
                                log.error("计算运输结算数据错误" + e.getMessage());
                                continue;
                            }
                        }
                        if (flag == 1) {
                            try {
                                materialBillService.calcMaterialDetail(beforeToday,origin.getId(), MaterialContractTypeEnum.ZC.getCode(), null, null, "系统管理员", 1);
                            } catch (Exception e) {
                                log.error("计算运输结算数据错误" + e.getMessage());
                                continue;
                            }
                            try {
                                materialBillService.calcMaterialDetail(beforeToday,origin.getId(), MaterialContractTypeEnum.YSC.getCode(), null, null, "系统管理员", 1);
                            } catch (Exception e) {
                                log.error("计算运输结算数据错误" + e.getMessage());
                                continue;
                            }
                            if (beforeToday.indexOf("-12") != -1) {
                                try {
                                    materialBillService.calcMaterialDetail(beforeToday + "附",origin.getId(), MaterialContractTypeEnum.ZC.getCode(), null, null, "系统管理员", 1);
                                } catch (Exception e) {
                                    log.error("计算运输结算数据错误" + e.getMessage());
                                    continue;
                                }
                                try {
                                    materialBillService.calcMaterialDetail(beforeToday + "附",origin.getId(), MaterialContractTypeEnum.YSC.getCode(), null, null, "系统管理员", 1);
                                } catch (Exception e) {
                                    log.error("计算运输结算数据错误" + e.getMessage());
                                    continue;
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            redisUtils.releaseLock(MATERIAL_WEIGHT_REDIS_LOOK_KEY);
        }
    }

}
